#include <iostream>
#include <unistd.h>
#include <pthread.h>

// 1.观察id, pthread_self()获取 ,观察id (Hex打印)  打印出来的id本质是一个地址
// 2. 终止线程 1. return  2.pthread_exit() 3.exit() 终止进程（即所有线程全部终止）
// 3. 线程也是需要等待的 ，不然也会出现类似于僵尸进程的问题 pthread_join()
// 4. 返回值问题(void *) 什么都可以返回（类似于传参）
// 5. 线程是可以分离的（pthread_detach()）,线程分离以后，就不需要需要join了，jion获取到的数据就没有意义了，os自动回收分离线程资源
// 线程默认joinable状态的，可以被设置为分离状态
// 6.线程是可以被取消的(pthread_canle())
// 
class ThreadReturn
{
public:
    ThreadReturn(const std::string &info, int code, pthread_t id)
        : _info(info), _code(code), _id(id)
    {
    }

public:
    std::string _info;
    int _code;
    pthread_t _id;
};

std::string ToHex(pthread_t tid)
{
    char hex[64];
    snprintf(hex, sizeof(hex), "0x%lx", tid);
    return hex;
}

void *ThreadRoutine(void *arg)
{
    pthread_detach(pthread_self());
    std::string threadname = static_cast<const char *>(arg);
    int cnt = 5;
    while (true)
    {
        std::cout << "new thread name : " << threadname << ", new thread id : " << ToHex(pthread_self()) << std::endl;
        sleep(1);
    }
    // return nullptr;
    // pthread_exit(nullptr);
    // exit(10);
    // return (void *)"new thread done";
    // pthread_exit((void *)"new thread done");
    // return (void* )10;
    ThreadReturn *res = new ThreadReturn("new thread done !!!!", 20, pthread_self()); // 堆上的空间
    return (void *)res;
}




int main()
{
    pthread_t tid;
    pthread_create(&tid, nullptr, ThreadRoutine, (void *)"thread 1");


    //线程分离
    // int n = pthread_detach(tid);
    // std::cout << "detach return  n : " << n << std::endl;

    //线程取消
    sleep(5);
    int n = pthread_cancel(tid);
    std::cout << "new thraed cancel done ! n : " << n << std::endl;

    void *res = nullptr;
    n = pthread_join(tid, &res);

    // ThreadReturn *re = static_cast<ThreadReturn *>(res);
    // std::cout << "new thread done , n : " << n << " return val : "
    //           << " info :" << re->_info << " code : " << re->_code << " id : " << ToHex(re->_id) << std::endl;
    std::cout << "join n : " << n << " return val : " <<(int64_t)res << std::endl;

    // while(true)
    // {
    //     std::cout << "main thread runing !" << ", main tid : "<< ToHex(pthread_self()) << std::endl;
    //     sleep(1);
    // }
    return 0;
}
